﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Security;
using PNProject.EF;
using PNProject.Models;
using System.Globalization;

namespace PNProject.Controllers
{
    public class ProductDetailsController : Controller
    {
        public ActionResult Index(int CatelogId, Guid id)
        {
            var member = Membership.GetUser();
            if (member != null)
            {
                var userName = member.UserName;
                Utils.TrackingUser(null, userName, "ProductDetailsController", "Index", Request.Url.PathAndQuery.ToString());
            }

             var proModel = new ProductDetailModel();
            var pros = StaticData.GetAllProductByCatalog(CatelogId);
            var product = pros.FirstOrDefault(a => a.ProductID == id);
            proModel.Product = product;
            proModel.CatelogId = product.CategoryID;
            var rela = pros.Where(a => a.ProductID != id);
            proModel.RelateProducts = rela.Any() ? rela.Take(3) : new List<Product>();
            VisitModel visit = new VisitModel();
            var vs = StaticData.settingRepo.GetOne(a => a.SKey == "visit");
            if (vs != null)
            {
                var arr = vs.SValue.Split('*');
                visit.Today = PNLibraries.PNVietNamNumberFormat(long.Parse(arr[0]), ",");
                visit.Month = PNLibraries.PNVietNamNumberFormat(long.Parse(arr[1]), ",");
                visit.Total = PNLibraries.PNVietNamNumberFormat(long.Parse(arr[2]), ",");
            }
            proModel.VisitModel = visit;
            var subMenu = StaticData.cmenuRepo.GetSome(a => a.ProductID == id).OrderByDescending(a=>a.LastUpdate);
            if (subMenu.Any())
            {
                proModel.SubMenu = subMenu.ToList();
            }
            else
            {
                proModel.SubMenu = new List<CMenu>();
            }
            proModel.AllowComment = product.AllowComment;
            var strId = id.ToString();
            var comments = StaticData.commentRepo.GetSome(a => a.TargetID == strId);
            proModel.CommentModels= new CommentModels();
            if (comments.Any())
            {
                var pageSize = 3;
                var pageIndex = 1;
                proModel.CommentModels.Comments = comments.Take(pageSize); 
                proModel.CommentModels.ProductId = strId;
                var totalPage = comments.Count() / pageSize;
                if (comments.Count()%pageSize != 0)
                    totalPage++;
                proModel.CommentModels.TotalPageComment = totalPage <= 1 ? 1 : totalPage++;
                proModel.CommentModels.AllowComment = proModel.AllowComment;
                var totalComment = comments.Count();
                proModel.CommentModels.TotalComment = totalComment;
                proModel.CommentModels.PageIndex = pageIndex;
                var min = pageSize * (pageIndex - 1) + 1;
                var max = min + proModel.CommentModels.Comments.Count()-1;
                proModel.CommentModels.ShowRecord = min + "-" + max;
              }

            bool lang = CultureInfo.CurrentUICulture.Name == "vi-VN" ? true : false;
            var cate = StaticData.cateRepo.GetOne(a => a.CategoryID == product.CategoryID);
            if (lang)
                ViewData["caname"] = cate.CategoryName;
            else
                ViewData["caname"] = cate.CategoryNameEN;
            ViewData["caid"] = cate.CategoryID;
            var ip = GetVisitorIpAddress();
            var productIp = new ProductIP
                            {
                                IP = ip,
                                CreateDate = DateTime.Now,
                                ProductId = id,
                                Id = Guid.NewGuid(),
                                IpId = null
                            };
            StaticData.productIpRepo.Save(null,productIp);
            if (member == null)
            {
                var productIps = StaticData.GetProductByIP(ip, id);
                if (productIps.Any())
                {
                    string timesVisit = WebConfigurationManager.AppSettings["TimesVisit"].ToString();
                    var countTimes = productIps.Count();
                    if (countTimes % int.Parse(timesVisit)==0)
                    {
                        proModel.TimeView = 1;
                    }
                }
            }
            return View(proModel);
        }
        public string GetVisitorIpAddress()
        {
            string stringIpAddress;
            stringIpAddress = Request.Params["HTTP_X_FORWARDED_FOR"];
            if (stringIpAddress == null) //may be the HTTP_X_FORWARDED_FOR is null
            {
                stringIpAddress = Request.Params["REMOTE_ADDR"];//we can use REMOTE_ADDR
            }
            return stringIpAddress;
        }
        [HttpPost]
        public ActionResult SubmitComment(Guid id, string mess)
        {
            var member = Membership.GetUser();
            if (member != null)
            {
                var userName = member.UserName;
                Utils.TrackingUser(null, userName, "ProductDetailsController", "SubmitComment", Request.Url.PathAndQuery.ToString());
            }

            var comment = new Comment();
            comment.CommentID = Guid.NewGuid();
            comment.Message = mess;
            //comment.Username =
            comment.SentDate = DateTime.Now;
            comment.Type = 0;
            comment.TargetID = id.ToString();
            StaticData.commentRepo.Save(null,comment);
           
            return Json(new {retult = true}, JsonRequestBehavior.AllowGet);
        }
       

        [HttpPost]
        public ActionResult PagingComments(string id, int pageIndex, int pageSize, bool AllowComment)
        {
            var member = Membership.GetUser();
            if (member != null)
            {
                var userName = member.UserName;
                Utils.TrackingUser(null, userName, "ProductDetailsController", "PagingComments", Request.Url.PathAndQuery.ToString());
            }

            var model = new CommentModels();
            var comments = StaticData.commentRepo.GetSome(a => a.TargetID == id);
            if (comments.Any())
            {
                var totalComment = comments.Count();
                model.TotalComment = totalComment;
                model.PageIndex = pageIndex;
                var paginCommnets = comments.Skip(pageSize*(pageIndex - 1)).Take(pageSize);
                model.Comments = paginCommnets;
                model.ProductId = id;
                var totalPage = comments.Count() == 1 ? 1 : comments.Count()/pageSize;
                if (totalPage != 1)
                {
                    if (paginCommnets.Count()%pageSize != 0)
                        totalPage = totalPage + 1;
                }
            
                model.TotalPageComment = totalPage <= 1 ? 1 : totalPage + 1;
                model.AllowComment = AllowComment;
                var min = pageSize*(pageIndex - 1) + 1;
                var max = min + model.Comments.Count()-1;
                model.ShowRecord = min + "-" + max;
                
            }
          
            return PartialView("DetailCommentContent",model);
        }
        [HttpPost]
        public ActionResult LogContentDetails(string mess)
        {
            var member = Membership.GetUser();
            if (member != null)
            {
                var userName = member.UserName;
                Utils.TrackingUser(null, userName, "ProductDetailsController", "LogContentDetails", Request.Url.PathAndQuery.ToString(), mess);
            }
            return Json(new { retult = true }, JsonRequestBehavior.AllowGet);
        }
        
    }
}
